﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Register : System.Web.UI.Page
{
    Validation validation;
    Sanitize sanitize;
 

    protected void Page_Load(object sender, EventArgs e)
    {
        validation = new Validation();
        sanitize = new Sanitize();
        if(!IsPostBack)
        {
            txtCaptcha.Text = "";
            SetCaptchaText();
        }        
    }



    private void SetCaptchaText()
    {
        Random oRandom = new Random();
        int iNumber = oRandom.Next(100000, 999999);
        Session["Captcha"] = iNumber.ToString();
    }

    protected void CreateButton_Click(object sender, EventArgs e)
    {                
        string newUsername = Username.Text;
        string newPassword = Password.Text;
        string newPasswordRepeat = PasswordRepeat.Text;
        string newEmail = Email.Text;

        if (validation.LoginValidation(newUsername, newPassword, newPasswordRepeat, newEmail))
        {
            if (CaptchaValidation())
            {
                // Spara uppgifterna i databasen. 
                Service service = new Service();
                Hashing hash = new Hashing();
                UserCredentials userC = new UserCredentials();
                userC.Username = newUsername;
                userC.Salt = hash.GetRandomSalt();
                userC.Password = hash.HashPassword(newPassword, userC.Salt);
                userC.Email = sanitize.EncodeText(newEmail);

                service.SaveUserCredentials(userC);
                LoggEntry loggEntry = new LoggEntry();
                loggEntry.Details = String.Format("A new user has been registered with the username : {0}", newUsername);
                loggEntry.IP = Request.UserHostAddress;
                service.SaveLoggEntry(loggEntry);
                //UCD.NewUserCredentials(newUsername, newPassword, "testEmail");
                Response.Redirect(ResolveUrl("~/SuccessfulRegistration.aspx"));
            }
        }
        
        DisplayAllErrorMessages();
        
    }


    private bool CaptchaValidation() 
    {
        if (txtCaptcha.Text == null)
        {
            txtCaptcha.Text = "";
        }
        if (Session["Captcha"].ToString() != txtCaptcha.Text.Trim())
        {
            AddErrorMessage("The Captcha Was Wrong");
            return false;
        }
        else
        {
            return true;
        }
    }


    private void DisplayAllErrorMessages()
    {
        List<string> errormessages = validation.GetErrorMessages();

        if (errormessages != null)
        {
            foreach (string error in errormessages)
            {
                AddErrorMessage(error);
            }
        }
    }

    #region  AddErrorMessage

    private void AddErrorMessage(string message)
    {
        Validators.Add(new CustomValidator
        {
            ErrorMessage = message,
            IsValid = false
        });
    }

    private void AddErrorMessage(IDataErrorInfo obj)
    {
        obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .Where(n => !String.IsNullOrWhiteSpace(obj[n])) // vill bara ha de som inte är tomma.
            .ToList()  // gör om till lista.
            .ForEach(n => AddErrorMessage(obj[n]));  // loopar igenom namnen som återstår o lägger till.
    }

    #endregion


}